﻿using System;
using com.IronOne.BoardPACWinApp.Common;
using com.IronOne.BoardPACWinAppUtil.Util;
using Windows.UI.Xaml;
using com.IronOne.BoardPACWinAppService.Agenda;
using System.Threading.Tasks;
using com.IronOne.BoardPACWinAppBO.General;
using com.IronOne.BoardPACWinAppBO.Paper;
using System.Collections.Generic;
using com.IronOne.BoardPACWinApp.Helpers;
using com.IronOne.BoardPACWinAppUtil.Enums;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace com.IronOne.BoardPACWinApp.View.UserControl.SettingPanels
{
    /// <summary>
    ///     An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class SettingAnnotationBackup
    {
        private readonly IAgendaService _agendaService;
        private readonly IDialogService _dialogService;

        public SettingAnnotationBackup()
        {
            InitializeComponent();
            _agendaService = new AgendaService();
            _dialogService = new DialogService();
        }

        private async void SettingAnnotationBackup_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                await BackupInfoInit();
            }
            catch (Exception)
            {
            }
        }

        private async void BackupButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                BackupProgressPanel.Visibility = Visibility.Visible;
                BackupButton.IsEnabled = false;
                BackupErrorTxt2.Visibility = Visibility.Collapsed;
                                
                List<PaperModel> data = await _agendaService.GetBackupNeededAnnotationsList();
                if (data == null || data.Count <= 0)
                {
                    BackupProgressPanel.Visibility = Visibility.Collapsed;
                    await _dialogService.ShowMessage("Everyting is already backup successfully.");
                    await BackupInfoInit();
                    return;
                }

                int cou = data.Count;
                string count = cou.ToString();
                int inc = 0;
                int errorCount = 0;
                ResponseDataModel rdm = new ResponseDataModel();

                foreach (var item in data)
                {
                    inc++;
                    int perc = (inc * 100) / cou;
                    string fileStr = (cou) == 1 ? " file" : " files";
                    BackupStatusTxt.Text = + perc + "% complete." + " (Backup " + inc + " of " + count  + fileStr + ")";
                    BackupProgressbar.Value = perc;
                    rdm = await _agendaService.BackupAnnotations(item);
                    if (!rdm.IsError)
                    {
                        await _agendaService.UpdateIsAnnotBackupNeededOnVersionTable(item.PaperId, item.VersionId, -1, false);
                        continue;
                    }
                    errorCount++;
                }

                await BackupInfoInit();

                if (rdm.IsError || errorCount > 0)
                {
                    BackupProgressPanel.Visibility = Visibility.Collapsed;
                    BackupErrorTxt2.Visibility = Visibility.Visible;
                                        
                    string msg1 = (errorCount == 1)? " file" : " files";
                    string msg = "Backup failed on " + errorCount + msg1;
                    BackupErrorTxt2.Text = msg;
                    return;
                }

                await _agendaService.SetAnnotationBackupDates();
                await _dialogService.ShowMessage("Backup successful");
            }
            catch (Exception)
            {
                BackupProgressPanel.Visibility = Visibility.Collapsed;
                BackupErrorTxt2.Visibility = Visibility.Visible;
                BackupErrorTxt2.Text = "Backup encountered an error";
            }
            finally
            {
                BackupProgressPanel.Visibility = Visibility.Collapsed;
                BackupButton.IsEnabled = true;
            }
        }

        private async void RestoreButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                RestoreProgressPanel.Visibility = Visibility.Visible;
                RestoreButton.IsEnabled = false;
                RestoreErrorTxt1.Visibility = Visibility.Collapsed;

                List<PaperModel> data = await _agendaService.DownloadRestoreNeededAnnotationsList();
                if (data == null || data.Count <= 0)
                {
                    RestoreProgressPanel.Visibility = Visibility.Collapsed;
                    await _dialogService.ShowMessage("Everyting is already restored successfully.");
                    return;
                }

                int cou = data.Count;
                string count = cou.ToString();
                int inc = 0;
                int errorCount = 0;
                ResponseDataModel rdm = new ResponseDataModel();
                RestoreProgressbar.IsIndeterminate = false;

                foreach (var item in data)
                {
                    inc++;
                    int perc = (inc * 100) / cou;
                    string fileStr = (cou) == 1 ? " file" : " files";
                    RestoreStatusTxt.Text = +perc + "% complete." + " (Restoring " + inc + " of " + count + fileStr + ")";
                    RestoreProgressbar.Value = perc;
                    rdm = await _agendaService.RestoreAnnotations(item);
                    if (!rdm.IsError)
                    {
                        //await _agendaService.UpdateRestoreAnnotationTable(item.RefId, PaperDownloadStatuses.Downloded);
                        continue;
                    }
                    errorCount++;
                }

                if (rdm.IsError || errorCount > 0)
                {
                    RestoreProgressPanel.Visibility = Visibility.Collapsed;
                    RestoreErrorTxt1.Visibility = Visibility.Visible;

                    string msg1 = (errorCount == 1) ? " file" : " files";
                    string msg = "Restore failed on " + errorCount + msg1;
                    RestoreErrorTxt1.Text = msg;
                    return;
                }

                await _dialogService.ShowMessage("Restore successful");
            }
            catch (Exception)
            {
                RestoreProgressPanel.Visibility = Visibility.Collapsed;
                RestoreErrorTxt1.Visibility = Visibility.Visible;
                RestoreErrorTxt1.Text = "Restore encountered an error";
            }
            finally
            {
                RestoreProgressPanel.Visibility = Visibility.Collapsed;
                RestoreButton.IsEnabled = true;
            }
        }


        private async Task BackupInfoInit()
        {
            try
            {
                /// <summary>
                /// [0] - IsBackupOnOff
                /// [1] - Backup duration in days
                /// [2] - Formatted datetime of last backup
                /// [3] - Formatted datetime of next backup
                string[] data = await _agendaService.GetAnnotationBackupDates();

                BackupErrorTxt1.Visibility = Visibility.Collapsed;
                if (data[0].Equals("0")) //backup is off
                {
                    BackupButton.Visibility = Visibility.Collapsed;
                    BackupErrorTxt1.Visibility = Visibility.Visible;
                }

                string dayt = (data[1].Equals("1")) ? " day" : " days";
                DurationTxt.Text = "Automatic backup frequency: " + data[1] + dayt;

                if (String.IsNullOrWhiteSpace(data[2])) data[2] = "Never";
                if (String.IsNullOrWhiteSpace(data[3])) data[3] = "Never";

                LastTxt.Text = "Last backup on: " + data[2];
                NextTxt.Text = "Next backup scheduled on: " + data[3];
                
                List<PaperModel> annData = await _agendaService.GetBackupNeededAnnotationsList();
                if (annData == null || annData.Count <= 0)
                    InfoTxt.Text = "Backup needed on: 0 files";
                else
                {
                    string dayy = (annData.Count == 1) ? " file" : " files";
                    InfoTxt.Text = "Backup needed on: " + annData.Count + dayy;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}